//
//  DataProcessor.m
//  RobstepToolsM2
//
//  Created by LCR on 13-9-12.
//  Copyright (c) 2013年 Robstep. All rights reserved.
//

#import "DataProcessor.h"

@implementation DataProcessor

- (id)init
{
    self = [super init];
    if (self) {
        cacheData = [NSMutableData data];
    }
    return self;
}

- (void)processInputData:(NSData*)data
{
    Byte byte[data.length];
    [data getBytes:byte];
    
    for (int i = 0; i <data.length; i++) {
        //               NSLog(@"byte[%i]=>%x", i, byte[i]);
        [self processByByte:byte[i]];
    }
}


- (void)processByByte:(Byte)data
{
    [cacheData appendBytes:&data length:1];
    
    switch (status) {
        case RX_data_start1:
            if (DATA_START == data) {
                status = RX_data_start2;
            } else {
                [cacheData replaceBytesInRange:NSMakeRange(0, cacheData.length) withBytes:NULL length:0];
            }
            break;
        case RX_data_start2:
            if (DATA_START == data)
                status = RX_data_end1;
            else {
                status = RX_data_start1;
                [cacheData replaceBytesInRange:NSMakeRange(0, cacheData.length) withBytes:NULL length:0];
            }
            break;
        default:
            if (cacheData.length == (NET_COMU_SIZE-1)) {
                if (data == DATA_END) {
                    status = RX_data_end2;
                } else {
                    status = RX_data_start1;
                    [cacheData replaceBytesInRange:NSMakeRange(0, cacheData.length) withBytes:NULL length:0];
                }
            }
            break;
        case RX_data_end2:
            if (data == DATA_END) {
                if (cacheData.length == NET_COMU_SIZE) {
                    struct NetComuDataPkt_t msg;
                    [cacheData getBytes:&msg];
                    [self.delegate getCAN_msg:msg.data];
                }
            }
            [cacheData replaceBytesInRange:NSMakeRange(0, cacheData.length) withBytes:NULL length:0];
            status = RX_data_start1;
            break;
    }
}

@end
